<template>
  <div class="in-number">
    <button
      class="btn btn-right"
      @click="reduceNumber(-1)"
      :disabled="currentValue === min"
    >
      -
    </button>
    <input
      :value="currentValue"
      @blur="handleInputEvent"
      @keyup.enter="handleInputEvent"
    />
    <button
      class="btn btn-left"
      @click="reduceNumber(1)"
      :disabled="currentValue === max"
    >
      +
    </button>
  </div>
</template>

<script lang="ts">
export default {
  name: "INnumber",
  props: {
    value: {
      type: Number,
    },
    min: {
      type: Number,
      default: 0,
    },
    max: {
      type: Number,
      default: 20,
    },
  },
  data() {
    return {
      currentValue: this.value,
    };
  },
  methods: {
    reduceNumber(num) {
      this.currentValue += num;
    },
    // imput 输入框的值赋值 事件是焦点事件 ，但可能不是Number类型
    handleInputEvent(event) {
      this.currentValue = event.target.value;
    },
  },
  //   监视是不是number或者超过最小值或则最大值
  watch: {
    currentValue(newVal, oldVal) {
      //  console.log(newVal, oldVal);

      const { min, max } = this;
      //  可能是小数点，向上取整
      let newValue = Math.ceil(+newVal);
      // console.log(newValue);

      // 判断是否是数字，非数字就新值等于旧值
      if (Number.isNaN(newValue)) {
        newValue = oldVal;
      }
      //如果小于最小值 就==最小值
      if (newValue < min) {
        newValue = min;
      }
      if (newValue > max) {
        newValue = max;
      }
      this.$emit("addCart", newValue);

      this.currentValue = newValue;
    },
  },
};
</script>

<script lang="ts" setup></script>

<style lang="less" scoped>
.in-number {
  width: 88px;
  height: 22px;
  border: 1px solid #a4adc4;
  display: flex;
  justify-content: space-between;
  text-align: center;
  line-height: 22px;
  .btn {
    width: 21px;
  }
  .btn-right {
    border-right: 1px solid #a4adc4;
  }
  .btn-left {
    border-left: 1px solid #a4adc4;
  }
  .btn-right:disabled,
  .btn-left:disabled {
    color: #ccc;
    cursor: not-allowed;
  }
  input {
    text-align: center;
    width: 40px;
    outline: none;
    border: none;
  }
}
</style>